package com.hly.musicbackground.model.index.rest;

import com.hly.musicbackground.Final.VersionFinal;
import com.hly.musicbackground.Utils.*;
import com.hly.musicbackground.model.index.service.impl.FileServiceImpl;
import com.hly.musicbackground.result.Code;
import com.hly.musicbackground.result.Result;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.FileOutputStream;

@RestController
@RequestMapping("/api/file")
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
@Api(tags = "文件")
public class FileController {

    private final FileServiceImpl service;
    private final IPUtils ipUtils;
    private final PathUtils pathUtils;
    private final Base64Utils base64Utils;

    @PostMapping("/upload")
    @ApiOperation(value = "文件上传")
    public Result upload(MultipartFile file, @RequestParam(value = "name") String name,
                         @RequestParam(value = "type", defaultValue = VersionFinal.ANDROID) String type){

        if (StringUtils.isEmpty(name)){
            Code.BUSINESS_ERR("版本号/名称不能为空");
        }

        String originalFilename = file.getOriginalFilename();
        int index = originalFilename.indexOf(".");

        if (VersionFinal.ANDROID.equals(type) || VersionFinal.WINDOWS.equals(type)){
            name = "/cli/" + type + "-" + name + originalFilename.substring(index);
        }else {
            Code.BUSINESS_ERR("请选择正确的类型");
        }

        try {
            FileOutputStream stream = new FileOutputStream(pathUtils.path + name);
            stream.write(file.getBytes());
            stream.close();
        }catch (Exception e){
            Code.BUSINESS_ERR("上传失败");
        }

        return Result.ok("http://" + ipUtils.IP + ":" + ipUtils.port + "/static" + name);
    }
}
